#!/usr/bin/env pwsh
# 服务健康监控脚本
# 功能：每隔30秒检查一次服务健康状态，发现问题立即报警

param(
    [int]$Interval = 30,  # 检查间隔（秒）
    [string]$Url = "http://localhost:8215"
)

$ErrorActionPreference = "Continue"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  SPI.AgentServer 健康监控脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "监控配置：" -ForegroundColor Yellow
Write-Host "  - 服务地址：$Url" -ForegroundColor White
Write-Host "  - 检查间隔：$Interval 秒" -ForegroundColor White
Write-Host "  - 开始时间：$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor White
Write-Host ""
Write-Host "按 Ctrl+C 停止监控" -ForegroundColor Gray
Write-Host ""

$consecutiveFailures = 0
$totalChecks = 0
$totalFailures = 0
$startTime = Get-Date

function Test-ServiceHealth {
    param([string]$endpoint)
    
    try {
        $response = Invoke-WebRequest -Uri $endpoint -Method Get -TimeoutSec 5 -UseBasicParsing
        return @{
            Success = $true
            StatusCode = $response.StatusCode
            ResponseTime = 0
        }
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
            StatusCode = 0
        }
    }
}

function Format-Uptime {
    param([TimeSpan]$duration)
    
    if ($duration.TotalDays -ge 1) {
        return "{0}天{1}小时" -f [int]$duration.TotalDays, $duration.Hours
    }
    elseif ($duration.TotalHours -ge 1) {
        return "{0}小时{1}分钟" -f [int]$duration.TotalHours, $duration.Minutes
    }
    elseif ($duration.TotalMinutes -ge 1) {
        return "{0}分钟" -f [int]$duration.TotalMinutes
    }
    else {
        return "{0}秒" -f [int]$duration.TotalSeconds
    }
}

try {
    while ($true) {
        $checkTime = Get-Date
        $totalChecks++
        
        # 检查基础健康端点
        $healthCheck = Test-ServiceHealth "$Url/api/health"
        
        if ($healthCheck.Success) {
            $consecutiveFailures = 0
            $uptime = $checkTime - $startTime
            $successRate = [math]::Round((($totalChecks - $totalFailures) / $totalChecks) * 100, 2)
            
            Write-Host "[$(Get-Date -Format 'HH:mm:ss')] " -NoNewline -ForegroundColor Gray
            Write-Host "✅ 服务正常 " -NoNewline -ForegroundColor Green
            Write-Host "| 运行时长: $(Format-Uptime $uptime) " -NoNewline -ForegroundColor Cyan
            Write-Host "| 成功率: $successRate% " -NoNewline -ForegroundColor Cyan
            Write-Host "| 检查次数: $totalChecks" -ForegroundColor Gray
        }
        else {
            $consecutiveFailures++
            $totalFailures++
            
            Write-Host "[$(Get-Date -Format 'HH:mm:ss')] " -NoNewline -ForegroundColor Gray
            Write-Host "❌ 服务异常 " -NoNewline -ForegroundColor Red
            Write-Host "| 连续失败: $consecutiveFailures 次 " -NoNewline -ForegroundColor Yellow
            Write-Host "| 错误: $($healthCheck.Error)" -ForegroundColor Red
            
            # 连续失败3次发出警报
            if ($consecutiveFailures -eq 3) {
                Write-Host ""
                Write-Host "🚨🚨🚨 严重警告 🚨🚨🚨" -ForegroundColor Red -BackgroundColor Yellow
                Write-Host "服务已连续 3 次健康检查失败！" -ForegroundColor Red -BackgroundColor Yellow
                Write-Host "请立即检查服务状态！" -ForegroundColor Red -BackgroundColor Yellow
                Write-Host ""
                
                # Windows系统发出声音警报
                [Console]::Beep(1000, 500)
                Start-Sleep -Milliseconds 200
                [Console]::Beep(1000, 500)
            }
        }
        
        # 每隔10次检查，进行详细健康检查
        if ($totalChecks % 10 -eq 0) {
            Write-Host ""
            Write-Host "📊 详细健康检查 (第 $totalChecks 次)" -ForegroundColor Cyan
            
            $detailedCheck = Test-ServiceHealth "$Url/api/health/detailed"
            if ($detailedCheck.Success) {
                Write-Host "   ✅ 详细检查通过" -ForegroundColor Green
            }
            else {
                Write-Host "   ⚠️ 详细检查失败: $($detailedCheck.Error)" -ForegroundColor Yellow
            }
            Write-Host ""
        }
        
        Start-Sleep -Seconds $Interval
    }
}
catch {
    Write-Host ""
    Write-Host "监控已停止：$($_.Exception.Message)" -ForegroundColor Yellow
}
finally {
    $endTime = Get-Date
    $totalUptime = $endTime - $startTime
    
    Write-Host ""
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "  监控统计报告" -ForegroundColor Cyan
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "总检查次数：$totalChecks" -ForegroundColor White
    Write-Host "失败次数：$totalFailures" -ForegroundColor White
    Write-Host "成功率：$([math]::Round((($totalChecks - $totalFailures) / $totalChecks) * 100, 2))%" -ForegroundColor White
    Write-Host "监控时长：$(Format-Uptime $totalUptime)" -ForegroundColor White
    Write-Host "========================================" -ForegroundColor Cyan
}



